package com.mine.androidlearn.common.base;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.mine.androidlearn.GlobalApplication;

import java.util.concurrent.locks.ReentrantLock;


/**
 * mvp模式下Activity的基类
 *
 * @author mine
 * @version V1.0 2018/8/5 15:57
 */
public abstract class BaseMvpActivity<V extends IBaseView, T extends BasePresenter<V>> extends AppCompatActivity {

    protected GlobalApplication mGlobalApplication; //application
    protected T mPresenter;
    private ProgressDialog mProgressDialog = null; // 加载对话框
    private final ReentrantLock mReentrantLock = new ReentrantLock();

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mGlobalApplication = (GlobalApplication) getApplication();

        // 创建Presenter
        mPresenter = createPresenter();

        initVariables();
        initViews(savedInstanceState);
        loadData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //关联View
        mPresenter.attachView((V) this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //解除关联View
        mPresenter.detachView();
    }

    @Override
    protected void onDestroy() {
        mPresenter.detachView();
        super.onDestroy();

        // 加入内存泄漏监视队列
        GlobalApplication.getRefWatcher().watch(this);
    }

    /**
     * 创建Presenter
     */
    protected abstract T createPresenter();

    /**
     * 初始化变量
     */
    protected abstract void initVariables();

    /**
     * 初始化视图
     *
     * @param savedInstanceState
     */
    protected abstract void initViews(Bundle savedInstanceState);

    /**
     * 加载数据
     */
    protected abstract void loadData();

    /**
     * 显示loading对话框
     *
     * @param title
     * @param cancelable
     * @return void
     */
    protected void showLoadingDialog(String title, boolean cancelable) {
        mReentrantLock.lock();
        try {
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }
            if (mProgressDialog == null) {
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setCancelable(cancelable);
            }
            mProgressDialog.setMessage(title);
            mProgressDialog.show();
        } finally {
            mReentrantLock.unlock();
        }
    }

    /**
     * 关闭loading对话框
     *
     * @return void
     */
    protected void hideLoadingDialog() {
        mReentrantLock.lock();
        try {
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }
        } finally {
            mReentrantLock.unlock();
        }
    }
}
